using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;

namespace SheLife.Api.Controllers
{
    /// <summary>
    /// 习惯管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HabitsController : ControllerBase
    {
        private readonly IHabitService _habitService;

        public HabitsController(IHabitService habitService)
        {
            _habitService = habitService;
        }

        /// <summary>
        /// 获取习惯详情
        /// </summary>
        /// <param name="id">习惯ID</param>
        /// <returns>习惯详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetHabit(Guid id)
        {
            var habit = await _habitService.GetHabitByIdAsync(id);
            if (habit == null)
            {
                return NotFound();
            }

            return Ok(habit);
        }

        /// <summary>
        /// 获取用户的习惯列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="type">习惯类型</param>
        /// <param name="isActive">是否激活</param>
        /// <returns>习惯列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetHabits(
            [FromQuery] Guid userId,
            [FromQuery] string? type = null,
            [FromQuery] bool? isActive = null)
        {
            var habits = await _habitService.GetHabitsByUserIdAsync(userId, type, isActive);
            return Ok(habits);
        }

        /// <summary>
        /// 创建习惯
        /// </summary>
        /// <param name="model">习惯创建模型</param>
        /// <returns>创建的习惯</returns>
        [HttpPost]
        public async Task<IActionResult> CreateHabit([FromBody] CreateHabitModel model)
        {
            try
            {
                var habit = await _habitService.CreateHabitAsync(
                    model.UserId,
                    model.Name,
                    model.Description,
                    model.Type,
                    model.Icon,
                    model.Color,
                    model.TargetFrequency,
                    model.TargetValue,
                    model.StartDate,
                    model.EndDate);

                return CreatedAtAction(nameof(GetHabit), new { id = habit.Id }, habit);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新习惯
        /// </summary>
        /// <param name="id">习惯ID</param>
        /// <param name="model">习惯更新模型</param>
        /// <returns>更新后的习惯</returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateHabit(Guid id, [FromBody] UpdateHabitModel model)
        {
            var habit = await _habitService.UpdateHabitAsync(
                id,
                model.Name,
                model.Description,
                model.Type,
                model.Icon,
                model.Color,
                model.TargetFrequency,
                model.TargetValue,
                model.StartDate,
                model.EndDate);

            if (habit == null)
            {
                return NotFound();
            }

            return Ok(habit);
        }

        /// <summary>
        /// 激活习惯
        /// </summary>
        /// <param name="id">习惯ID</param>
        /// <returns>激活结果</returns>
        [HttpPost("{id}/activate")]
        public async Task<IActionResult> ActivateHabit(Guid id)
        {
            var result = await _habitService.ActivateHabitAsync(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(new { message = "习惯激活成功" });
        }

        /// <summary>
        /// 停用习惯
        /// </summary>
        /// <param name="id">习惯ID</param>
        /// <returns>停用结果</returns>
        [HttpPost("{id}/deactivate")]
        public async Task<IActionResult> DeactivateHabit(Guid id)
        {
            var result = await _habitService.DeactivateHabitAsync(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(new { message = "习惯停用成功" });
        }

        /// <summary>
        /// 删除习惯
        /// </summary>
        /// <param name="id">习惯ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHabit(Guid id)
        {
            var result = await _habitService.DeleteHabitAsync(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(new { message = "习惯删除成功" });
        }

        /// <summary>
        /// 获取护肤习惯
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>护肤习惯列表</returns>
        [HttpGet("skincare")]
        public async Task<IActionResult> GetSkincareHabits([FromQuery] Guid userId)
        {
            var habits = await _habitService.GetHabitsByUserIdAsync(userId, "Skincare", true);
            return Ok(habits);
        }

        /// <summary>
        /// 创建护肤习惯
        /// </summary>
        /// <param name="model">护肤习惯创建模型</param>
        /// <returns>创建的护肤习惯</returns>
        [HttpPost("skincare")]
        public async Task<IActionResult> CreateSkincareHabit([FromBody] CreateSkincareHabitModel model)
        {
            try
            {
                // 将护肤步骤数据序列化为JSON
                var data = new
                {
                    model.Steps,
                    model.Products,
                    model.Reminders
                };

                var habit = await _habitService.CreateHabitAsync(
                    model.UserId,
                    model.Name,
                    model.Description,
                    "Skincare",
                    model.Icon,
                    model.Color,
                    model.TargetFrequency,
                    null,
                    model.StartDate,
                    model.EndDate);

                return CreatedAtAction(nameof(GetHabit), new { id = habit.Id }, habit);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 习惯创建模型
    /// </summary>
    public class CreateHabitModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 习惯名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 习惯描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 习惯类型
        /// </summary>
        public string Type { get; set; } = string.Empty;

        /// <summary>
        /// 图标
        /// </summary>
        public string? Icon { get; set; }

        /// <summary>
        /// 颜色
        /// </summary>
        public string? Color { get; set; }

        /// <summary>
        /// 目标频率
        /// </summary>
        public string TargetFrequency { get; set; } = string.Empty;

        /// <summary>
        /// 目标值
        /// </summary>
        public int? TargetValue { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? EndDate { get; set; }
    }

    /// <summary>
    /// 习惯更新模型
    /// </summary>
    public class UpdateHabitModel
    {
        /// <summary>
        /// 习惯名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 习惯描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 习惯类型
        /// </summary>
        public string Type { get; set; } = string.Empty;

        /// <summary>
        /// 图标
        /// </summary>
        public string? Icon { get; set; }

        /// <summary>
        /// 颜色
        /// </summary>
        public string? Color { get; set; }

        /// <summary>
        /// 目标频率
        /// </summary>
        public string TargetFrequency { get; set; } = string.Empty;

        /// <summary>
        /// 目标值
        /// </summary>
        public int? TargetValue { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? EndDate { get; set; }
    }

    /// <summary>
    /// 护肤习惯创建模型
    /// </summary>
    public class CreateSkincareHabitModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 习惯名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 习惯描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 图标
        /// </summary>
        public string? Icon { get; set; }

        /// <summary>
        /// 颜色
        /// </summary>
        public string? Color { get; set; }

        /// <summary>
        /// 目标频率
        /// </summary>
        public string TargetFrequency { get; set; } = string.Empty;

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? EndDate { get; set; }

        /// <summary>
        /// 护肤步骤
        /// </summary>
        public List<SkincareStep>? Steps { get; set; }

        /// <summary>
        /// 使用产品
        /// </summary>
        public List<SkincareProduct>? Products { get; set; }

        /// <summary>
        /// 提醒设置
        /// </summary>
        public List<Reminder>? Reminders { get; set; }
    }

    /// <summary>
    /// 护肤步骤
    /// </summary>
    public class SkincareStep
    {
        /// <summary>
        /// 步骤名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 步骤顺序
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        /// 步骤描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 预计时间（分钟）
        /// </summary>
        public int? EstimatedMinutes { get; set; }
    }

    /// <summary>
    /// 护肤产品
    /// </summary>
    public class SkincareProduct
    {
        /// <summary>
        /// 产品名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand { get; set; }

        /// <summary>
        /// 产品类型
        /// </summary>
        public string? Type { get; set; }

        /// <summary>
        /// 使用步骤
        /// </summary>
        public int Step { get; set; }
    }

    /// <summary>
    /// 提醒设置
    /// </summary>
    public class Reminder
    {
        /// <summary>
        /// 提醒时间
        /// </summary>
        public TimeSpan Time { get; set; }

        /// <summary>
        /// 提醒日期（星期几）
        /// </summary>
        public List<DayOfWeek> Days { get; set; } = new List<DayOfWeek>();

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 提醒内容
        /// </summary>
        public string? Message { get; set; }
    }
}